<template>
  <div class="w-full bg-white rounded-lg shadow-md overflow-hidden">
    <!-- Calendar title bar -->
    <div class="bg-course-default text-white p-3 flex justify-between items-center">
      <h3 class="font-semibold">Course Calendar View</h3>
      <div class="text-sm">Current semester: Second semester of 2025</div>
    </div>
    <!-- FullCalendar container -->
    <div class="p-4">
      <FullCalendar :options="calendarOptions" @eventClick="handleEventClick" />
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import FullCalendar from '@fullcalendar/vue3'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import zhLocale from '@fullcalendar/core/locales/zh-cn'
import { calendarConfig } from '@/config/appConfig'

// 1. Receive the parent component course list (including startDate/endDate)
const props = defineProps({
  courses: {
    type: Array,
    default: () => []
  }
})

// 2. Define events (pass course click events to parent component for editing)
const emit = defineEmits(['courseClick'])

// 3. Calendar Event List (Responsive)
const calendarEvents = ref([])

// 4. Initialize calendarOptions first (ensuring priority order)
const calendarOptions = ref({
  plugins: [timeGridPlugin, interactionPlugin], // Essential plugins (time grid+interaction)
  initialView: calendarConfig.initialView,     // Initial view (from global configuration, such as timeGridWeek)
  slotMinTime: calendarConfig.slotMinTime,     // Minimum time displayed (e.g. 08:00:00)
  slotMaxTime: calendarConfig.slotMaxTime,     // The maximum displayed time (e.g. 18:00:00)
  hiddenDays: calendarConfig.hiddenDays,       // Hidden dates (such as weekends: [0,6])
  locale: zhLocale,                            // Chinese localization
  events: calendarEvents.value,                // Bind calendar events (responsive association)
  eventColor: '#3b82f6',                       // Default event color (overwritten by backgroundColor)
  eventTextColor: 'white',                     // Event Text Color
  headerToolbar: {
    left: 'prev,next today', // Left button group: Last month/Next month+Today
    center: 'title',         // Middle: Current date range (e.g. October 2025)
    right: ''                // Hide default view switch (only retaining timeGridWeek)
  },
  editable: false, // Do not drag and drop modifications (simplified version)
  selectable: false, // Prohibition of Time Range Selection (Simplified Version)
  eventContent: (info) => {
    // Customize event content (displaying course names and teacher line breaks)
    return {
      html: `<div class="text-center text-sm">${info.event.title.replace('\n', '<br>')}</div>`
    }
  }
})

// 5. Convert courses to calendar events (using startDate/endDate)
const convertCoursesToEvents = (courses) => {
  return courses.map(course => ({
    id: course.id || Date.now().toString(), // Unique ID (keep original ID when editing courses)
    title: `${course.name}\n${course.teacher}`, // Course name+teacher (displayed with line breaks)
    start: `${course.startDate}T${course.startTime}`, // Combine date and time (FullCalendar format required)
    end: `${course.endDate}T${course.endTime}`, // Combination end date+end time
    backgroundColor: course.isConflict ? '#ef4444' : '#3b82f6', // Conflict: Red, Normal: Blue
    borderColor: course.isConflict ? '#ef4444' : '#3b82f6',
    allDay: false, // Non all day events (display time period)
    extendedProps: { ...course } // Transfer complete course data (click to edit)
  }))
}

// 6. Monitor changes in the course list (update calendar events in real-time)
watch(() => props.courses, (newCourses) => {
  calendarEvents.value = convertCoursesToEvents(newCourses)
  // CalendarOptions.events is already bound to calendarEvents, automatically synchronized, no need for duplicate assignment
}, { immediate: true, deep: true })

// 7. Calendar event click processing (passing complete data to parent component for editing)
const handleEventClick = (info) => {
  info.jsEvent.preventDefault() // Block default browser redirection
  emit('courseClick', info.event.extendedProps) // Pass complete data containing startDate/endDate
}

// 8. Initialize calendar events during component mounting
onMounted(() => {
  calendarEvents.value = convertCoursesToEvents(props.courses)
})
</script>